<template>
    <el-card class="box-card">
        <template #header>
            <!-- 调用关闭方法 -->
            <el-icon @click="$emit('close', true); closedata()">
                <ArrowLeftBold />
            </el-icon>
            <span style="margin: 0 10px;">|</span>
            <span>新增</span>
        </template>
        <el-form label-position="right" label-width="100px" :model="FormData" style="max-width: 800px" ref="ruleFormRef"
            :rules="rules">
            <el-form-item label="封面图">
                <el-upload class="avatar-uploader" :show-file-list="false" action="dev-api/api/uploadimg/"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="FormData.draftCover" :src="FormData.draftCover" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="标题" prop="draftTitle">
                <el-input v-model="FormData.draftTitle" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="展览时间" prop="draftCoverTime">
                <el-date-picker v-model="FormData.draftCoverTime" type="datetime" placeholder="请选择起始日期和时间"
                    format="YYYY/MM/DD HH:mm:ss" value-format="YYYY-MM-DD h:m:s " />
            </el-form-item>
            <el-form-item label="位置" prop="draftCity">
                <el-input v-model="FormData.draftCity" placeholder="所在城市"></el-input>
            </el-form-item>
            <el-form-item label="所属分类" prop="FormData.draftSubClass_id_id">
                <el-cascader v-model="FormData.draftSubClass_id_id" :options="options" :props="cascadeDate"
                    @change="handleChange" />

            </el-form-item>
            <el-form-item label="内容">
                <div style="border: 1px solid #ccc">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
                    <Editor style="height: 200px; overflow-y: hidden;" v-model="FormData.draftContent"
                        @onCreated="handleCreated" />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button @click="$emit('close', true) ; closedata()">取消</el-button>
                <el-button @click="addData(ruleFormRef); " type="primary">保存</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script lang="ts" setup>
import { Plus, ArrowLeftBold } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from 'vue'
// elementplus表单验证
import type { FormInstance, FormRules } from 'element-plus'
// 富文本编辑器
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 文件上传组件
import type { UploadProps } from 'element-plus'

// 获取分类接口和添加数据接口
import { getClassifyData, addSolicitContributions } from "@/api/BackstageCallForPapers/index"

// 获取props中的数据


// 所属分类初始化配置
const cascadeDate = { value: "id", label: "name" }
// 
var FormData = reactive({
    draftCover: '',  // 图片地址
    draftTitle: '',  // 标题
    draftCity: "",  // 所在城市
    draftCoverTime: '',  // 征稿时间
    draftSubClass_id_id: 0,  // 	所属分类id
    draftContent: ""  // 内容
})

const ruleFormRef = ref<FormInstance>()
// 定义表单规则
const rules = reactive<FormRules>({
    draftTitle: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 3, max: 5, message: '长度3到5', trigger: 'blur' },
    ],
    draftCity: [{ required: true, message: '请输入位置', trigger: 'blur' },
    ],
    draftCoverTime: [
        {
            type: 'date',
            required: true,
            message: '请选择日期',
            trigger: 'change',
        },
    ],
    FormData:{
        draftSubClass_id_id: [
        {
            required: true,
            message: '请选择所属分类',
            trigger: 'change',
        },
    ]
    }   
})
// 所属分类信息
let options = ref([])
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 获取所属分类信息
onMounted(async () => {
    let res = await getClassifyData()
    options.value = res.data
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 获取图片上传地址
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    FormData.draftCover = response.path
}

// 获取所属分类id
const handleChange = (value: any) => {
    FormData.draftSubClass_id_id = value[value.length - 1]
}
// 限制上传图片的格式为jpg 
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图像须为.jpg格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图像大小不要超过5mb')
        return false
    }
    return true
}

// 关闭后将数据回归
let closedata = () => {
    console.log(FormData);
    FormData.draftCover = ''
    FormData.draftTitle = ''
    FormData.draftCity = ''
    FormData.draftSubClass_id_id = 0,
        FormData.draftContent = '',
        FormData.draftCoverTime = ''
}
// 定义回调函数
const emit = defineEmits(["close"])
// 添加数据
let addData = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let res = await addSolicitContributions(FormData)
            formEl.resetFields()
            emit('close', true)
        }
    })
}
</script>


<style lang="scss" scoped>
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    background-color: #f0f0f0;
}
</style>